# -*- coding: utf-8 -*-
'''考虑把term封装成类，用面向对象的方式实现以下函数
'''
from datetime import datetime, timedelta

from dateutil import parser

from common.utils import tz


CONFIGS = [     # standard time, no offset
    {'internal': 600, 'start': 10, 'end': 22},
    {'internal': 300, 'start': 22, 'end': 24},
    {'internal': 300, 'start': 0, 'end': 2},
]


def calc_term_by_ts(ts):
    '''通过绝对时间来计算期数（无偏移量）
    '''
    prefix, start_ts = tz.get_day_and_start_ts(ts)
    sub = ts - start_ts
    # 2 * 60 * 60
    if sub < 7200:   # 0 ~ 2点
        term = sub / 300 + 1
    # 10 * 60 * 60
    elif sub < 36000:    # 2 ~ 10点，第24期一直到25期开始才会开奖
        term = 24
    # 22 * 60 * 60
    elif sub < 79200:
        term = (sub - 36000) / 600 + 25
    else:
        term = (sub - 79200) / 300 + 97
    assert 1 <= term <= 120
    return '%s%s' % (prefix, str(term).zfill(3))


def _plus_term(day, real_term, offset):
    day_offset = offset / 120
    term_offset = offset % 120
    day += timedelta(days=day_offset)
    real_term += term_offset
    if real_term > 120:
        real_term -= 120
        day += timedelta(days=1)
    elif real_term < 0:  # term_offset可能为负数
        real_term += 120
        day -= timedelta(days=1)
    return day, real_term


def _format_term(day, real_term):
    return '%s%s' % (day.strftime('%Y%m%d'), str(real_term).zfill(3))


def plus_term(term, offset):
    '''计算期号，offset可以为负数
    '''
    if offset == 0:
        return term
    prefix, real_term = term[:8], int(term[8:])
    prefix, real_term = _plus_term(parser.parse(prefix), real_term, offset)
    return _format_term(prefix, real_term)


def xrange_term(term, count, step=1):
    '''生成器，根据plus term生成一个迭代器，类似xrange
    '''
    if step == 0:
        raise ValueError('step must be not 0')
    if count == 0:
        yield term
    cur_count = 0
    prefix, real_term = term[:8], int(term[8:])
    prefix = parser.parse(prefix)
    while abs(cur_count) < abs(count):
        cur_count += 1
        if cur_count == 1:
            yield term
        else:
            prefix, real_term = _plus_term(prefix, real_term, step)
            yield _format_term(prefix, real_term)


def calc_start_ts_by_term(term):
    '''通过期数计算开始时间，用来手动开启当前期数（无偏移量）
    '''
    prefix = term[:8]
    term = int(term[8:])
    start_ts = tz.to_ts(tz.local_to_utc(parser.parse(prefix)))
    if term <= 24:
        return start_ts + (term - 1) * 300
    elif term <= 96:
        # 10 * 60 * 60
        return start_ts + (term - 25) * 600 + 36000
    else:
        # 22 * 60 * 60
        return start_ts + (term - 97) * 300 + 79200


def calc_stop_ts(start_ts):
    '''根据开始时间和当前的时间，来计算结束的时间，无偏移量
    '''
    term = calc_term_by_ts(start_ts)
    real_term = int(term[8:])
    if real_term == 24:
        return start_ts + 29100
    elif 25 <= real_term < 97:
        return start_ts + 600
    else:
        return start_ts + 300
